import React, { FC, useEffect, useState } from 'react'
import { changeSize } from '@utils/electron'
import { Button, Divider, message, PageHeader, Tabs } from 'antd'
import { history } from 'umi'
import { getAllDatabaseList } from '@/services/database'
import { PlusOutlined } from '@ant-design/icons/lib'
import DatabaseConfigForm from '@pages/DatabaseConfig/components/DatabaseConfigForm'
const { TabPane } = Tabs

interface DatabaseConfigProps {
  location:any,
}

const DatabaseConfig: FC<DatabaseConfigProps> = (props) => {

  const [activeKey, setActiveKey] = useState<any>(' ')
  const [tableList, setTableList] = useState<any>([])

  useEffect(() => {
    getData();
    changeSize(900, 740, '数据库配置')
  }, [])

  const getData = () => {
    getAllDatabaseList().then(res => {
      if (res.code === 10000) {
        setTableList(res.data)
        setActiveKey(`${res.data[0]?.id}`)
      }
    })
  }

  const addDatabase = () => {
    if (tableList[0]?.id == 0) {
      message.warn('只能同时添加一个数据库！')
      return
    }

    const data = {id:'0',db_name:'New Database'}
    tableList.unshift(data);
    setTableList(tableList)
    setActiveKey('0')
  }

  return (
    <div style={{ backgroundColor: '#fff' }}>
      <PageHeader
        onBack={() => history.push('/')}
        title="数据库配置"
        subTitle='同步数据库'
      />
      <Divider style={{ margin: 0 }}/>
      <div style={{ textAlign: 'center' }}>
        <Button style={{ width: '80%', marginBottom: 10, marginTop: 20 }} type="dashed" onClick={addDatabase} block  icon={<PlusOutlined/>}>
          新建数据库
        </Button>
      </div>
      <Tabs style={{ height: 580 }} tabPosition='left' activeKey={activeKey} onChange={(key) => setActiveKey(key)}>
        {tableList.map((item: any, index: number) => (
          <TabPane key={item.id} tab={item.db_name}>
            <DatabaseConfigForm again={getData} dbId={item.id}/>
          </TabPane>
        ))}
      </Tabs>
    </div>
  )
}

export default DatabaseConfig
